package com.example.clientsideapplication;

import java.sql.Date;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ModifyOfferActivity extends Activity {

	private TextView newProductNameTW, newProductPriceTW, newProductInfoTW, newDataStartTW, newDataEndTW;
	private RadioButton checkedRadioButton;
	private RadioGroup newRadioGroup;
	private String productName;
	private Double productPrice;
	private String productInfo;
	private String category;
	private int currentDay, currentMonth, currentYear;
	private int startDay, startMonth, startYear;
	private int endDay, endMonth, endYear;
	private int previousStartDay, previousStartMonth, previousStartYear;
	private int previousEndDay, previousEndMonth, previousEndYear;
	private Date currentDate, startDate, endDate;
	private Button startButton, endButton;
	private RadioButton rb1, rb2, rb3, rb4, rb5;
	private int idOffer;
	private int serverSocket;
	private String serverAddress;
	private Intent intentView;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		productPrice = new Double(-1);
		setContentView(R.layout.modify_offer);

		intentView = getIntent();
		serverAddress = intentView.getStringExtra("serverAddress");
		serverSocket = intentView.getIntExtra("serverSocket", 21111);

		initModify();
	}

	public void onClickModifyOffer(View view) {

		Intent intent = new Intent(this, ModifyOfferService.class);
		
		// Date inizia il conteggio degli anni da 1900 e quello dei mesi da 0, quindi devo sottrarre 1900 agli anni
		// e 1 ai mesi, per ottenere la data corretta.
		startDate = new Date(startYear - 1900, startMonth - 1, startDay);
		endDate = new Date(endYear - 1900, endMonth - 1, endDay);
		
		// Sommo e sottraggo 1 al mese per mantenere i valori corretti.
		Calendar calendar = Calendar.getInstance();
		currentDay = calendar.get(Calendar.DAY_OF_MONTH);
		currentMonth = calendar.get(Calendar.MONTH) + 1;
		currentYear = calendar.get(Calendar.YEAR);
		currentDate = new Date(currentYear - 1900, currentMonth - 1, currentDay);
		
		
		checkedRadioButton = (RadioButton) findViewById(newRadioGroup
				.getCheckedRadioButtonId());
		
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_LONG;
		if (newProductNameTW.getText().toString().length() == 0) {
			Toast toast = Toast
					.makeText(
							context,
							"Campo \"Nome Prodotto\" vuoto, inserire un nome per il prodotto.",
							duration);
			toast.show();
			newProductNameTW.requestFocus();
		} else if (newProductPriceTW.getText().toString().length() == 0) {
			Toast toast = Toast
					.makeText(
							context,
							"Campo \"Prezzo Prodotto\" vuoto, inserire un prezzo per il prodotto.",
							duration);
			toast.show();
			newProductPriceTW.requestFocus();
		} else if (newProductInfoTW.getText().toString().length() == 0) {
			Toast toast = Toast
					.makeText(
							context,
							"Campo \"Info Prodotto\" vuoto, inserire delle info per il prodotto.",
							duration);
			toast.show();
			newProductInfoTW.requestFocus();
		} else if (endDate.compareTo(startDate) < 0) {
			Toast toast = Toast
					.makeText(
							context,
							"La data di fine offerta deve essere successiva alla data di inizio offerta indicata, modificare le date.",
							duration);
			toast.show();
		} else if (startDate.compareTo(currentDate) < 0) {
			Toast toast = Toast
					.makeText(
							context,
							"La data di inizio offerta non deve essere precedente alla data odierna, modificare la data di inizio.",
							duration);
			toast.show();
		} else {

			Offer offer = new Offer(checkedRadioButton.getText().toString(),
					newProductNameTW.getText().toString(), newProductInfoTW
							.getText().toString(), startDate, endDate,
					Double.parseDouble(newProductPriceTW.getText().toString()));
			
			intent.putExtra("offer", offer);
			intent.putExtra("idOffer", idOffer);
			intent.putExtra("serverAddress", serverAddress);
			intent.putExtra("serverSocket", serverSocket);
			
			startService(intent);
			
			Toast toast = Toast
					.makeText(
							context,
							"Modifica effettuata con successo.",
							duration);
			toast.show();

			finish();

		}

	}

	public void onClickReset(View view) {
		newProductNameTW.setText(productName);
		newProductPriceTW.setText(productPrice.toString());
		newProductInfoTW.setText(productInfo);

		if (category.compareTo("Alimentari") == 0)
			rb1.setChecked(true);
		else if (category.compareTo("Casalinghi") == 0)
			rb2.setChecked(true);
		else if (category.compareTo("Informatica") == 0)
			rb3.setChecked(true);
		else if (category.compareTo("Vestiario") == 0)
			rb4.setChecked(true);
		else if (category.compareTo("Telefonia") == 0)
			rb5.setChecked(true);

		startUpdate(previousStartDay, previousStartMonth, previousStartYear);
		endUpdate(previousEndDay, previousEndMonth, previousEndYear);
	}

	private void initModify() {
		newProductNameTW = (TextView) findViewById(R.id.modify_product_name_edit_text);
		newProductPriceTW = (TextView) findViewById(R.id.modify_product_price_edit_text);
		newProductInfoTW = (TextView) findViewById(R.id.modify_product_info_edit_text);
		newRadioGroup = (RadioGroup) findViewById(R.id.modify_offer_radio_group);
		newDataStartTW = (TextView) findViewById(R.id.modify_start_date);
		newDataEndTW = (TextView) findViewById(R.id.modify_end_date);
		rb1 = (RadioButton) findViewById(R.id.modify_offer_radio_button_1);
		rb2 = (RadioButton) findViewById(R.id.modify_offer_radio_button_2);
		rb3 = (RadioButton) findViewById(R.id.modify_offer_radio_button_3);
		rb4 = (RadioButton) findViewById(R.id.modify_offer_radio_button_4);
		rb5 = (RadioButton) findViewById(R.id.modify_offer_radio_button_5);
		
		getIntentValue();
		initOffer();
	}

	private void initOffer() {

		newProductNameTW.setText(productName);
		newProductPriceTW.setText(productPrice.toString());
		newProductInfoTW.setText(productInfo);

		if (category.compareTo("Alimentari") == 0)
			rb1.setChecked(true);
		else if (category.compareTo("Casalinghi") == 0)
			rb2.setChecked(true);
		else if (category.compareTo("Informatica") == 0)
			rb3.setChecked(true);
		else if (category.compareTo("Vestiario") == 0)
			rb4.setChecked(true);
		else if (category.compareTo("Telefonia") == 0)
			rb5.setChecked(true);

		startUpdate(startDay, startMonth, startYear);
		endUpdate(endDay, endMonth, endYear);
		newDataStartTW.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(0);
			}
		});
		newDataEndTW.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(1);
			}
		});
	}

	private void getIntentValue() {
		productName = intentView.getStringExtra("productName");
		productPrice = intentView.getDoubleExtra("productPrice", productPrice);
		productInfo = intentView.getStringExtra("productInfo");
		category = intentView.getStringExtra("category");
		idOffer = intentView.getIntExtra("idOffer", idOffer);
		startDay = intentView.getIntExtra("giornoInizio", startDay);
		startMonth = intentView.getIntExtra("meseInizio", startMonth) + 1;
		startYear = intentView.getIntExtra("annoInizio", startYear) + 1900;
		endDay = intentView.getIntExtra("giornoFine", endDay);
		endMonth = intentView.getIntExtra("meseFine", endMonth) +1;
		endYear = intentView.getIntExtra("annoFine", endYear) + 1900;
		previousStartDay = startDay;
		previousStartMonth = startMonth;
		previousStartYear = startYear;
		previousEndDay = endDay;
		previousEndMonth = endMonth;
		previousEndYear = endYear;
	}

	protected Dialog onCreateDialog(int id) {
		if (id == 0) {
			return new DatePickerDialog(this, startListener, startYear, startMonth - 1, startDay);
		} else {
			return new DatePickerDialog(this, endListener, endYear, endMonth - 1, endDay);
		}
	}

	protected DatePickerDialog.OnDateSetListener startListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker datePicker, int year, int month,
				int day) {
			// Il DataPicker prende il mese precedente, probabilmente inizia a contare da 0, quindi sommo 1.
			startDay = day;
			startMonth = month + 1;
			startYear = year;
			startUpdate(startDay, startMonth, startYear);
		}
	};

	protected void startUpdate(int day, int month, int year) {

		newDataStartTW.setText(new StringBuilder().append(day).append("-")
				.append(month).append("-").append(year)
				.append(" "));
	}

	protected DatePickerDialog.OnDateSetListener endListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker datePicker, int year, int month,
				int day) {
			// Il DataPicker prende il mese precedente, probabilmente inizia a contare da 0, quindi sommo 1.
			endDay = day;
			endMonth = month + 1;
			endYear = year;
			endUpdate(endDay, endMonth, endYear);
		}
	};

	protected void endUpdate(int day, int month, int year) {
		newDataEndTW.setText(new StringBuilder().append(day).append("-")
				.append(month).append("-").append(year).append(" "));
	}

}
